import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  Query,
  UploadedFile,
  UseInterceptors,
  BadRequestException,
} from '@nestjs/common'
import { PluginManagerService } from '../services/plugin-manager.service'
import { PluginMarketService } from '../services/plugin-market.service'
import { FileInterceptor } from '@nestjs/platform-express'
import { Permissions } from 'src/common/decorators/permissions.decorator'

/**
 * 插件管理API
 */
@Controller('plugins')
export class PluginController {
  constructor(
    private readonly pluginManager: PluginManagerService,
    private readonly pluginMarket: PluginMarketService,
  ) {}

  /** 获取所有插件列表 */
  @Get()
  @Permissions('plugin:list')
  listPlugins() {
    return this.pluginManager.getAllPlugins()
  }

  /** 启用插件 */
  @Post('enable/:name')
  @Permissions('plugin:enable')
  async enablePlugin(@Param('name') name: string) {
    await this.pluginManager.enablePlugin(name)
    return { success: true, message: `Plugin ${name} enabled` }
  }

  /** 禁用插件 */
  @Post('disable/:name')
  @Permissions('plugin:disable')
  async disablePlugin(@Param('name') name: string) {
    await this.pluginManager.disablePlugin(name)
    return { success: true, message: `Plugin ${name} disabled` }
  }

  /** 卸载插件 */
  @Post('uninstall/:name')
  @Permissions('plugin:uninstall')
  async uninstallPlugin(@Param('name') name: string) {
    await this.pluginManager.uninstallPlugin(name)
    return { success: true, message: `Plugin ${name} uninstalled` }
  }

  /** 市场搜索插件 */
  @Get('market/search')
  @Permissions('plugin:market:search')
  async searchMarket(@Query('q') q: string) {
    return this.pluginMarket.searchPlugins(q)
  }

  /** 市场获取插件详情 */
  @Get('market/:name')
  @Permissions('plugin:market:read')
  async getMarketPlugin(@Param('name') name: string) {
    return this.pluginMarket.getPluginDetails(name)
  }

  /** 市场下载插件 */
  @Post('market/download')
  @Permissions('plugin:market:download')
  async downloadMarketPlugin(@Body() body: { name: string; version: string }) {
    const filePath = await this.pluginMarket.downloadPlugin(body.name, body.version)
    // 解压、注册等略
    return { success: true, filePath }
  }

  /**
   * 上传插件并转发到市场
   * @param file 插件zip包
   * @param body 插件元数据
   */
  @Post('market/submit')
  @UseInterceptors(FileInterceptor('package'))
  @Permissions('plugin:market:submit')
  async submitPlugin(@UploadedFile() file: Express.Multer.File, @Body('metadata') metadata: string) {
    if (!file) throw new BadRequestException('未上传插件包')
    let pluginData: Record<string, unknown>
    try {
      pluginData = JSON.parse(metadata) as Record<string, unknown>
    } catch {
      throw new BadRequestException('metadata 不是合法JSON')
    }
    // file.buffer 是 Buffer
    const result = await this.pluginMarket.submitPlugin(pluginData, file.buffer)
    return { success: true, result }
  }
}
